<?php

require("./config.php");

if (!isset($_POST['req'])) {
    die("No request provided.");
} else {
    if (filter_input(INPUT_POST, 'req') == "registro") {
        $band = true;
        $json = array("success" => false, "msg" => "", "user" => "", "pss" => "");
        if (!isset($_SESSION['logged']) || $_SESSION['logged'] == "no") {

            $action = $dbConn->real_escape_string(filter_input(INPUT_POST, 'action'));
            $id = $dbConn->real_escape_string(filter_input(INPUT_POST, 'id'));
            $name = $dbConn->real_escape_string(filter_input(INPUT_POST, 'name'));
            $lastnam = $dbConn->real_escape_string(filter_input(INPUT_POST, 'lastnam'));
            $phone = $dbConn->real_escape_string(filter_input(INPUT_POST, 'phone'));
            $phone2 = $dbConn->real_escape_string(filter_input(INPUT_POST, 'phone2'));
            $mail = $dbConn->real_escape_string(filter_input(INPUT_POST, 'mail'));
            $pass = $dbConn->real_escape_string(filter_input(INPUT_POST, 'pass'));
            $enterprise = $dbConn->real_escape_string(filter_input(INPUT_POST, 'enterprise'));
            $siglas = $dbConn->real_escape_string(filter_input(INPUT_POST, 'siglas'));
            $tam = $dbConn->real_escape_string(filter_input(INPUT_POST, 'tam'));
            $desc = $dbConn->real_escape_string(filter_input(INPUT_POST, 'desc'));
            $dir = $dbConn->real_escape_string(filter_input(INPUT_POST, 'dir'));
            $area = $dbConn->real_escape_string(filter_input(INPUT_POST, 'area'));

            $hashed_pass = better_crypt($pass);

            $idempresa;
            if ($action == 0) {
                $queryInsEmpresa = "insert into EMPRESA values(DEFAULT,'" . $enterprise . "',"
                        . "'" . $siglas . "','" . $tam . "','" . $desc . "','" . $dir . "');";
                $resultInsEmp = $dbConn->query($queryInsEmpresa);

                if ($resultInsEmp != null) {
                    $queryConsEmpresa = "SELECT Max(PK_EMPRESA_CODIGO_EMPRESA) ULTIMO FROM EMPRESA";
                    $resultConsEmp = $dbConn->query($queryConsEmpresa);

                    $info = $resultConsEmp->fetch_row();
                    $idempresa = $info[0];
                }
            } else {
                $idempresa = $action;
            }

            $query = "insert into USUARIO values('" . $id . "','" . $hashed_pass . "','contacto',true);";
            $result = $dbConn->query($query);

            if ($result != null) {
                $query0 = "insert into CONTACTO "
                        . "values('" . $id . "','" . $name . "','" . $lastnam . "'," .
                        $phone . "," . $phone2 . ",'" . $mail . "','" . $area .
                        "','" . $idempresa . "');";
                $result0 = $dbConn->query($query0);

                $json["succes"] = true;
                $json["msg"] = "Se ha registrado correctamente, se iniciará sesión automáticamente!";
                $json["user"] = $id;
                $json["pss"] = $pass;
            } else {
                $json["succes"] = false;
                $json["msg"] = "Este usuario ya se encuentra registrado, si olvidó la contraseña por favor utilice la opción ,para recuperar la contraseña, que está en el inicio de sesión";
            }
        }
        print(json_encode($json));
    } else if (filter_input(INPUT_POST, 'req') == "empresas") {

        $json = array("success" => false, "rowCount" => 0, "Elements" => Array());

        $query = "Select PK_EMPRESA_CODIGO_EMPRESA, NOMBRE_EMPRESA, SIGLAS_EMPRESA from EMPRESA ORDER BY NOMBRE_EMPRESA ASC";

        $result = $dbConn->query($query);
        $i = 0;
        while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
            array_push($json['Elements'], $row);
            $i++;
        }
        if ($i > 0) {
            $json['success'] = true;
            $json['rowCount'] = $i;
        }

        print(json_encode($json));
    } else if (filter_input(INPUT_POST, 'req') == "consEmpresa") {
        $codEmp = $dbConn->real_escape_string(filter_input(INPUT_POST, 'codEmp'));

        $json = array("success" => false, "Elements" => Array());

        $query = "Select NOMBRE_EMPRESA, SIGLAS_EMPRESA, TAMAÑO_EMPRESA, DESCRIPCION_EMPRESA, DIRECCION_EMPRESA from EMPRESA where PK_EMPRESA_CODIGO_EMPRESA='" . $codEmp . "'";

        $result = $dbConn->query($query);
        $i = 0;
        while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
            array_push($json['Elements'], $row);
            $i++;
        }

        if ($i > 0) {
            $json['success'] = true;
        }

        print(json_encode($json));
    } else if (filter_input(INPUT_POST, 'req') == "generaPass") {
        $json = array("success" => false, "msg" => "");

        $pass = $dbConn->real_escape_string(filter_input(INPUT_POST, 'pass'));

        $hashed_pass = better_crypt($pass);

        $json["succes"] = true;
        $json["msg"] = $hashed_pass;

        print(json_encode($json));
    }
}